// 权限管理 - 权限列表接口
const Router = require("koa-router");
const router = new Router();
const Mock = require("mockjs");

// 自定义生成随机账号函数
Mock.Random.extend({
  account: function () {
    const chars =
      "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    const length = Mock.mock("@natural(6, 10)");
    let result = "";
    for (let i = 0; i < length; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
  },
});

// 权限数据结构
const generatePermissionData = (pageSize) => {
  return Mock.mock({
    [`list|${pageSize}`]: [
      {
        "id|+1": 10001,
        name: "@cname", // 姓名
        account: "@account", // 账号
        phone: /^1[3-9]\d{9}$/, // 电话
        idNo: "@id", // 身份证号
        "position|1": [
          "客服专员",
          "客服经理",
          "市场专员",
          "市场经理",
          "运营专员",
          "运营经理",
          "技术工程师",
          "技术经理",
          "Boss",
        ], // 职位
        "department|1": [
          "总裁办",
          "技术部",
          "市场部",
          "维修部",
          "运营部",
          "客服部",
        ], // 所属部门
        "pageAuthority|1": ["admin", "manager", "user", "自定义权限"], // 页面权限
        "btnAuthority|1": ["add", "delete", "edit", "all", "自定义权限"], // 按钮权限
        createTime: '@datetime("yyyy-MM-dd HH:mm:ss")', // 创建时间
        "status|1": [1, 2], // 1正常 2禁用
      },
    ],
    total: 41,
  });
};

// 创建固定数据备份（用于重置）
const fixedPermissionData = generatePermissionData(41);

/**
 * 权限列表接口
 * 路径：POST /permission/permissionList
 *
 * 请求参数：
 * {
 *   page: 1,            // 分页参数
 *   pageSize: 10,       // 分页大小
 *   name: "张三",       // 姓名（可选）
 *   account: "admin",   // 账号（可选）
 *   department: "技术部", // 部门（可选）
 *   position: "经理"    // 职位（可选）
 * }
 */
router.post("/permission/permissionList", (ctx) => {
  try {
    // 解析请求参数
    const requestBody = ctx.request.body;
    const {
      page = 1,
      pageSize = 10,
      name,
      account,
      department,
      position,
    } = requestBody;

    console.log("权限列表接口收到参数:", requestBody);

    // 筛选数据
    let filteredData = [...fixedPermissionData.list];

    // 按姓名筛选
    if (name) {
      filteredData = filteredData.filter((item) => item.name.includes(name));
    }

    // 按账号筛选
    if (account) {
      filteredData = filteredData.filter((item) =>
        item.account.includes(account)
      );
    }

    // 按部门筛选
    if (department) {
      filteredData = filteredData.filter(
        (item) => item.department === department
      );
    }

    // 按职位筛选
    if (position) {
      filteredData = filteredData.filter((item) =>
        item.position.includes(position)
      );
    }

    // 计算分页
    const pageNum = parseInt(page);
    const size = parseInt(pageSize);
    const startIndex = (pageNum - 1) * size;
    const endIndex = startIndex + size;
    const paginatedData = filteredData.slice(startIndex, endIndex);

    // 返回响应
    ctx.body = {
      code: 200,
      message: "操作成功",
      data: {
        list: paginatedData,
        total: filteredData.length,
      },
    };
  } catch (error) {
    console.error("权限列表接口出错:", error);
    ctx.body = {
      code: 500,
      message: `服务器内部错误: ${error.message}`,
      data: null,
    };
  }
});

/**
 * 权限统计接口
 * 路径：GET /permission/permissionStats
 *
 * 说明：此接口返回权限数据的统计信息
 */
router.get("/permission/permissionStats", (ctx) => {
  try {
    console.log("权限统计接口被调用");

    // 按部门统计
    const departmentStats = {};
    fixedPermissionData.list.forEach((item) => {
      if (!departmentStats[item.department]) {
        departmentStats[item.department] = 0;
      }
      departmentStats[item.department]++;
    });

    // 按职位统计
    const positionStats = {};
    fixedPermissionData.list.forEach((item) => {
      if (!positionStats[item.position]) {
        positionStats[item.position] = 0;
      }
      positionStats[item.position]++;
    });

    // 按页面权限统计
    const pageAuthorityStats = {};
    fixedPermissionData.list.forEach((item) => {
      if (!pageAuthorityStats[item.pageAuthority]) {
        pageAuthorityStats[item.pageAuthority] = 0;
      }
      pageAuthorityStats[item.pageAuthority]++;
    });

    // 按状态统计
    const statusStats = {
      正常: fixedPermissionData.list.filter((item) => item.status === 1).length,
      禁用: fixedPermissionData.list.filter((item) => item.status === 2).length,
    };

    // 返回统计信息
    ctx.body = {
      code: 200,
      message: "操作成功",
      data: {
        total: fixedPermissionData.list.length,
        departmentStats,
        positionStats,
        pageAuthorityStats,
        statusStats,
      },
    };
  } catch (error) {
    console.error("权限统计接口出错:", error);
    ctx.body = {
      code: 500,
      message: `服务器内部错误: ${error.message}`,
      data: null,
    };
  }
});

/**
 * 更新用户权限接口
 * 路径：POST /permission/updatePermission
 *
 * 请求参数：
 * {
 *   id: 10001,              // 用户ID
 *   pageAuthority: "admin", // 页面权限
 *   btnAuthority: "all"     // 按钮权限
 * }
 */
router.post("/permission/updatePermission", (ctx) => {
  try {
    // 解析请求参数
    const requestBody = ctx.request.body;
    const { id, pageAuthority, btnAuthority } = requestBody;

    console.log("更新权限接口收到参数:", requestBody);

    if (!id) {
      ctx.body = {
        code: 400,
        message: "缺少必要的参数: id",
        data: null,
      };
      return;
    }

    // 查找用户
    const userIndex = fixedPermissionData.list.findIndex(
      (item) => item.id == id
    );

    if (userIndex === -1) {
      ctx.body = {
        code: 404,
        message: `未找到ID为 ${id} 的用户`,
        data: null,
      };
      return;
    }

    // 更新权限
    if (pageAuthority) {
      fixedPermissionData.list[userIndex].pageAuthority = pageAuthority;
    }

    if (btnAuthority) {
      fixedPermissionData.list[userIndex].btnAuthority = btnAuthority;
    }

    // 返回响应
    ctx.body = {
      code: 200,
      message: "权限更新成功",
      data: fixedPermissionData.list[userIndex],
    };
  } catch (error) {
    console.error("更新权限接口出错:", error);
    ctx.body = {
      code: 500,
      message: `服务器内部错误: ${error.message}`,
      data: null,
    };
  }
});

// 导出路由
module.exports = router;
